<template>
  <div>
    <el-form
      :model="formData"
      inline
      style="display: flex;justify-content: flex-end;margin-top: 10px;"
    >
      <el-form-item prop="name">
        <el-input v-model="formData.name" placeholder="请输入优惠券名称"></el-input>
      </el-form-item>
      <el-form-item prop="type">
        <el-select v-model="formData.type" placeholder="请输入优惠券类型">
          <el-option
            v-for="(item, index) in typeOptions"
            :label="item.label"
            :value="item.value"
            :key="index">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="status">
        <el-select v-model="formData.status" placeholder="请输入优惠券状态">
          <el-option
            v-for="(item, index) in statusOptions"
            :label="item.label"
            :value="item.value"
            :key="index">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="search" type="primary">查找</el-button>
        <el-button @click="openDialog('创建', 'add', null)" type="primary">添加</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="tableLoading" :data="tableData" border>
      <el-table-column align="center" label="优惠券id" prop="id"></el-table-column>
      <el-table-column align="center" label="优惠券名称" prop="name"></el-table-column>
      <el-table-column align="center" label="介绍" prop="desc"></el-table-column>
      <el-table-column align="center" label="标签" prop="tag"></el-table-column>
      <el-table-column align="center" label="最低消费" prop="min">
        <template slot-scope="scope">
          {{`满${scope.row['min']}元可用`}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="满减金额" prop="discount">
        <template slot-scope="scope">
          {{`减免${scope.row['discount']}元可用`}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="每人限领" prop="limit"></el-table-column>
      <el-table-column align="center" label="商品适用范围" prop="test"></el-table-column>
      <el-table-column align="center" label="优惠券类型" prop="type">
        <template slot-scope="scope">
          {{scope.row['type'] | tableFilter(typeOptions)}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="优惠券数量" prop="total"></el-table-column>
      <el-table-column align="center" label="状态" prop="status">
        <template slot-scope="scope">
          {{scope.row['status'] | tableFilter(statusOptions)}}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="300"
        align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="toDetailPage(scope.row)" type="primary">详情</el-button>
          <el-button size="mini" @click="openDialog('编辑', 'edit', scope.row)" type="primary">编辑</el-button>
          <el-button size="mini" @click="deleteData(scope.row)" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageInfo.page"
      :page-sizes="[10, 20, 30, 50, 100]"
      :page-size="pageInfo.limit"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total">
    </el-pagination>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      width="500"
    >
      <el-form ref="dialogForm" :rules="formRules" :model="dialogFormData" label-width="100px">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="dialogFormData.name"></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="desc">
          <el-input v-model="dialogFormData.desc"></el-input>
        </el-form-item>
        <el-form-item label="标签" prop="tag">
          <el-input v-model="dialogFormData.tag"></el-input>
        </el-form-item>
        <el-form-item label="最低消费" prop="min">
          <el-input v-model="dialogFormData.min"></el-input>
        </el-form-item>
        <el-form-item label="满减金额" prop="discount">
          <el-input v-model="dialogFormData.discount"></el-input>
        </el-form-item>
        <el-form-item label="每人限领" prop="limit">
          <el-input v-model="dialogFormData.limit"></el-input>
        </el-form-item>
        <el-form-item label="分发类型" prop="type">
          <el-select v-model="dialogFormData.type" placeholder="请选择分发类型">
            <el-option
              v-for="(item, index) in typeOptions"
              :label="item.label"
              :value="item.value"
              :key="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券数量" prop="total">
          <el-input v-model="dialogFormData.total"></el-input>
        </el-form-item>
        <el-form-item label="有效期" prop="days">
          <el-button-group>
            <el-button @click="dayType = '0'" :type="dayType === '0' ? 'primary' : ''">领券相对天数</el-button>
            <el-button @click="dayType = '1'" :type="dayType === '1' ? 'primary' : ''">指定绝对时间</el-button>
          </el-button-group>

          <el-input v-show="dayType === '0'" v-model="dialogFormData.days"></el-input>

          <br>
          <el-date-picker
            @change="dayRangeChange"
            v-show="dayType === '1'"
            v-model="dayRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button @click="confirm" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import moment from 'moment'

export default {
  name: 'couponManagement',
  componentTitle: '优惠券管理',
  data () {
    return {
      tableLoading: false,
      dialogVisible: false,
      dialogTitle: '创建',
      dialogType: 'add',
      dayRange: [],
      dialogFormData: {
      },
      pageInfo: {
        page: 1,
        limit: 10,
        total: 0
      },
      formData: {
        name: '',
        type: '',
        status: ''
      },
      tableData: [],
      formRules: {
        question: [
          {required: true, message: '请输入问题', trigger: 'change'}
        ],
        answer: [
          {required: true, message: '请输入回答', trigger: 'change'}
        ]
      },
      typeOptions: [
        {label: '通用领券', value: 0},
        {label: '注册赠券', value: 1},
        {label: '注册码', value: 2}
      ],
      statusOptions: [
        {label: '正常', value: 0},
        {label: '已过期', value: 1},
        {label: '已下架', value: 2}
      ],
      // 0---领券相对天数
      // 1---指定绝对时间
      dayType: '0'
    }
  },
  mounted () {
    this.search()
  },
  filters: {
    tableFilter (value, options) {
      let index = options.findIndex(item => {
        return Number(item.value) === Number(value)
      })

      if (index < 0) {
        return '---'
      } else {
        return options[index].label
      }
    }
  },
  methods: {
    dayRangeChange (value) {
      console.log(value)
    },
    openDialog (title, type, row) {
      this.dialogVisible = true
      this.dialogType = type
      this.dialogTitle = title

      if (type === 'edit') {
        this.$nextTick(() => {
          this.dialogFormData = Object.assign({}, row)

          // console.log(row.startTime)
          // console.log(row.endTime)
          this.dayRange = [new Date(row.startTime), new Date(row.endTime)]
        })
      }
    },
    confirm () {
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          if (this.dialogType === 'add') {
            this.addData()
          } else if (this.dialogType === 'edit') {
            this.editData()
          }
        } else {
          return false
        }
      })
    },
    cancel () {
      this.$refs.dialogForm.resetFields()
      this.dialogVisible = false
    },
    // 添加接口
    addData () {
      axios({
        url: 'http://192.168.200.251:8888/admin/coupon/create',
        method: 'post',
        data: {
          ...this.dialogFormData,
          timeType: Number(this.dayType),
          startTime: this.dayRange[0] ? moment(this.dayRange[0]).format('yyyy-MM-DD HH:mm:ss') : '',
          endTime: this.dayRange[1] ? moment(this.dayRange[1]).format('yyyy-MM-DD HH:mm:ss') : '',
          goodsType: 0,
          goodsValue: [],
          status: 0
        },
        headers: {
         'shopping-admin-token': sessionStorage.getItem('shopping-admin-token')
        }
      }).then(res => {
        if (res.data.errno === 0) {
          this.cancel()
          this.$notify.success({title: '添加成功'})

          this.search()
        } else {
          this.$notify.error({title: '添加失败'})
        }
      })
    },
    // 编辑接口
    editData () {
      axios({
        url: 'http://192.168.200.251:8888/admin/coupon/update',
        method: 'post',
        data: {
          ...this.dialogFormData
        },
        headers: {
          'shopping-admin-token': sessionStorage.getItem('shopping-admin-token')
        }
      }).then(res => {
        if (res.data.errno === 0) {
          this.cancel()
          this.$notify.success({title: '编辑成功'})

          this.search()
        } else {
          this.$notify.error({title: '编辑失败'})
        }
      })
    },
    toDetailPage (row) {
      this.$router.push({
        path: '/couponManagement/detail',
        query: {
          id: row.id
        }
      })
    },
    deleteData (row) {
      this.$confirm('此操作将删除该问题, 是否继续?').then(() => {
        axios({
          url: 'http://192.168.200.251:8888/admin/coupon/delete',
          method: 'post',
          data: row,
          headers: {
            'shopping-admin-token': sessionStorage.getItem('shopping-admin-token')
          }
        }).then(res => {
          this.$notify.success({title: '删除成功'})
  
          this.search()
        })
      })
    },
    search () {
      this.tableLoading = true

      axios({
        url: 'http://192.168.200.251:8888/admin/coupon/list',
        method: 'get',
        params: {
          page: this.pageInfo.page,
          limit: this.pageInfo.limit,
          ...this.formData
        },
        headers: {
          'shopping-admin-token': sessionStorage.getItem('shopping-admin-token')
        }
      }).then(res => {
        this.tableLoading = false
        this.tableData = res.data.data.list.map(item => {
          return Object.assign({}, item, {
            test: '全场通用'
          })
        })

        this.pageInfo.total = res.data.data.total
        console.log(res)
      })
    },
    // 每页多少条切换
    handleSizeChange (value) {
      this.pageInfo.limit = value

      this.search()
    },
    // 当前页码的切换
    handleCurrentChange (value) {
      this.pageInfo.page = value

      this.search()
    }
  }
}
</script>
